/*
 *  This file is part of Cha++ers.
 *
 *  Cha++ers is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Cha++ers is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Cha++ers.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "src/libraries/config.h"
#include "src/libraries/text.h"

#define SETTINGSIZE 128
ConfigFile::ConfigFile(const char* cfile)
{
	FILE * pFile;
	long lSize;
	char * buffer;
	size_t result;

	pFile = fopen ( cfile , "rb" );
	if (pFile==NULL) {
		fputs ("File error",stderr);
		exit (1);
	}

	fseek (pFile , 0 , SEEK_END);
	lSize = ftell (pFile);
	rewind (pFile);

	buffer = (char*) malloc (sizeof(char)*lSize);
	if (buffer == NULL) {
		fputs ("Memory error",stderr);
		exit (2);
	}

	result = fread (buffer,1,lSize,pFile);
	if (result != (unsigned int)lSize) {
		fputs ("Reading error",stderr);
		exit (3);
	}

	char* pch = strtok(buffer,"\n");
	while (pch != NULL) {
		{
			std::string working = pch;
			if (working.find("=")) {
				values[working.substr(0,working.find("="))] = working.substr(working.find("=")+1);
			}
		}
		pch = strtok(NULL,"\n\r\t\b ");
	}


	fclose (pFile);
	if (buffer != NULL)free (buffer);
}

ConfigFile::~ConfigFile()
{

}

int ConfigFile::ValueExists(std::string setting)
{
	int retval = values.count(setting);
	return retval;
}

int ConfigFile::GetValue_Int(std::string setting)
{
	int retval = atoi(values[setting].c_str());
	return retval;
}

std::string ConfigFile::GetValue_String(std::string setting)
{
	return values[setting];
}
